import 'dart:convert';
import 'package:http/http.dart' as http;

/// AI聊天API响应模型
class AiChatResponse {
  final int code;
  final AiChatData? data;
  final String message;

  const AiChatResponse({required this.code, this.data, required this.message});

  factory AiChatResponse.fromJson(Map<String, dynamic> json) {
    return AiChatResponse(
      code: json['code'] as int,
      data: json['data'] != null ? AiChatData.fromJson(json['data']) : null,
      message: json['message'] as String? ?? '',
    );
  }
}

/// AI聊天数据模型
class AiChatData {
  final String? answer;
  final String? conversationId;
  final int? showSec;

  const AiChatData({this.answer, this.conversationId, this.showSec});

  factory AiChatData.fromJson(Map<String, dynamic> json) {
    return AiChatData(
      answer: json['answer'] as String?,
      conversationId: json['conversation_id'] as String?,
      showSec: json['show_sec'] as int?,
    );
  }
}

/// AI聊天API服务
class AiChatApiService {
  static const String _baseUrl = 'https://api.wiseaii.com/wiseai/v1';
  static const String _chatEndpoint = '/chat';
  static const String _bundleId = 'com.cult.app'; // 替换为您的实际bundle_id

  /// 发送消息到AI
  static Future<AiChatResponse> sendMessage({
    required String sessionId,
    required String content,
    String? conversationId,
  }) async {
    try {
      final url = Uri.parse('$_baseUrl$_chatEndpoint');

      final headers = {'Content-Type': 'application/json'};

      final body = {
        'bundle_id': _bundleId,
        'session_id': sessionId,
        'content_type': 'text',
        'content': content,
        if (conversationId != null) 'conversation_id': conversationId,
      };

      final response = await http.post(
        url,
        headers: headers,
        body: json.encode(body),
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body) as Map<String, dynamic>;
        return AiChatResponse.fromJson(jsonData);
      } else {
        throw Exception('HTTP ${response.statusCode}: ${response.body}');
      }
    } catch (e) {
      throw Exception('Failed to send message: $e');
    }
  }

  /// 检查API是否可用
  static Future<bool> checkApiAvailability() async {
    try {
      final response = await sendMessage(
        sessionId: 'test_${DateTime.now().millisecondsSinceEpoch}',
        content: 'test',
      );
      return response.code == 1003;
    } catch (e) {
      return false;
    }
  }
}
